package com.climb.moive.framework.jdbc;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class BeanPropertyRowMapper<T> implements RowMapper<T> {
    private Class<T> mappedClass;

    public BeanPropertyRowMapper(Class<T> mappedClass) {
        this.mappedClass = mappedClass;
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
       try {
            // 创建一个对象
            T mappedObject = mappedClass.getDeclaredConstructor().newInstance();

            // 获取结果集的元数据
            ResultSetMetaData metadata = rs.getMetaData(); // 结果集元数据
            // 结果集有几列数据
            int columnCount = metadata.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                // 列名
                String coulmnName = metadata.getColumnName(i);
                // 获取列的值
                Object coulmnData = rs.getObject(i);

                /*
                   反射实现：
                   1. 属性名和列名要相同
                 */
                //列对应的属性
                Field f = mappedClass.getDeclaredField(coulmnName);
                f.setAccessible(true);
                f.set(mappedObject, coulmnData);
            }

            return mappedObject;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}